#include "TileSheet.h"

TileSheet::TileSheet(QWidget* parent)
    :
    GLWindow(parent),
    myCamera(0, 0, 160, 480),
    myVerticalScroll(Qt::Vertical, this),
    myHorizontalScroll(Qt::Horizontal, this)
{
    myVerticalScroll.setMaximum(1);
    myHorizontalScroll.setMaximum(1);
    myVerticalScroll.setTracking(true);
    myHorizontalScroll.setTracking(true);
    connect(&myVerticalScroll, SIGNAL(valueChanged(int)), this, SLOT(MoveCameraY(int)));
    connect(&myHorizontalScroll, SIGNAL(valueChanged(int)), this, SLOT(MoveCameraX(int)));

    myVerticalScroll.resize(20, 460);
    myHorizontalScroll.resize(160, 20);

    myVerticalScroll.move(140,0);
    myHorizontalScroll.move(0, 460);

    myVerticalScroll.show();
    myHorizontalScroll.show();
    myImage = new Image;
    myDir = "cool.png";
    myCurrent = 0;
    size = 8;

}

TileSheet::~TileSheet()
{
    myRects.clear();
    if(myImage)
        delete myImage;
}

int TileSheet::GetTileID()
{
    return myCurrent;
}

void TileSheet::SetupRects()
{
    myRects.clear();
    for(int i = 0; i < myImage->GetClipRect().h; i+=size)
    {
        for(int j = 0; j <  myImage->GetClipRect().w; j+=size)
        {
            myRects.push_back(TileRect(j, i, size, size));
        }
    }
    myCurrent = 0;
}

void TileSheet::SelectTile(int mouseX, int mouseY)
{
    for(unsigned int i =0; i < myRects.size(); i++)
    {
        if(myRects[i].contains(mouseX, mouseY))
        {
            myCurrent = i;
            return;
        }
    }
}

void TileSheet::mousePressEvent(QMouseEvent* clicked)
{
    if(myRects.size() > 0)
        SelectTile(clicked->x() - myCamera.left(), clicked->y() - myCamera.top());
}

TileRect& TileSheet::GetRect(int index)
{
    return myRects[index];
}

TileRect& TileSheet::GetSelected()
{
    return myRects[myCurrent];
}

void TileSheet::SetImage(std::string name)
{
    myDir = name.c_str();
    updateGL();
    myImage->Load(myDir);
    myVerticalScroll.setMaximum(myImage->GetClipRect().h/size+1);
    myHorizontalScroll.setMaximum(myImage->GetClipRect().w/size+1);
    updateGL();
    SetupRects();

}

void TileSheet::initializeGL()
{
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glEnable(GL_TEXTURE_2D);
    myImage->Load(myDir);
    SetupRects();
}

void TileSheet::paintGL()
{
    glClearColor(170.f/255.f, 170.f/255.f, 170.f/255.f, 0.5f);
    glClear(GL_COLOR_BUFFER_BIT);
    glLoadIdentity();

    if(myImage)
        myImage->Render(myCamera.left(), myCamera.top());
}

void TileSheet::MoveCameraY(int y)
{
    myCamera.setTop(-y*size+1);
    updateGL();
}

void TileSheet::MoveCameraX(int x)
{
    myCamera.setLeft(-x*size+1);
    updateGL();
}
